package com.kurumi.medical.controller;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.kurumi.medical.model.HospitalVisitExaminationReportsInfo;
import com.kurumi.medical.model.HospitalVisitExaminationReportsItem;
import com.kurumi.medical.model.HospitalVisitExaminationReportsRecord;
import com.kurumi.medical.param.Report;
import com.kurumi.medical.param.ReportItem;
import com.kurumi.medical.param.ReportRoot;
import com.kurumi.medical.service.HospitalVisit305Service;
import com.kurumi.medical.util.Analysis_Xml;
import com.kurumi.medical.util.DateUtil;
import com.kurumi.medical.util.FileUtil;
import com.kurumi.medical.util.HttpClientUtil;
import com.kurumi.medical.util.Result;
import com.kurumi.medical.vo.BloodTransfusionVO;

@Controller
@RequestMapping("/report")
public class ReceiveReportController {
	
	@Autowired
	private HospitalVisit305Service hospitalVisit305Service;
	
	
	
	@ResponseBody
	@RequestMapping("/getBlood")
	public Object getBlood() throws ParseException {
		BloodTransfusionVO bloodTransfusionVO = new BloodTransfusionVO();
		bloodTransfusionVO.setId("D62028");
		bloodTransfusionVO.setInHospitalTime(DateUtil.dateParse("2010-02-01 00:00:00"));
		bloodTransfusionVO.setOutHospitalTime(DateUtil.dateParse("2011-02-01 00:00:00"));
		
		return hospitalVisit305Service.getBloodTransfusionList(bloodTransfusionVO);
	}
	
	public Date str2Date(String dateString) throws ParseException{
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.parse(dateString);
	}
	

	@ResponseBody
	@RequestMapping("/parseXml")
	public String parseXml(String fileName) throws IOException{
		FileReader reader = new FileReader(new File("D://xml/5027645.xml"));
		String str = "";
		char[] c = new char[1024];
		int length = 0;
		while((length = reader.read(c))!=-1) {
			str+=new String(c, 0, length);
		}
		

		
         Analysis_Xml.getCheckReportOrderDetailMsg2(str);
       
		 return "success";
	}

	@ResponseBody
	@RequestMapping("/index")
	public Object report() throws ParseException, IOException, DocumentException{
		Map<String,String> params = new HashMap<>();
		String mrId="D4207";
		params.put("soap_method", "GetIdsByMRN");
		params.put("mrn", mrId);
		params.put("startDate", "2017-11-27 09:01:02");
		params.put("endDate", "2017-12-01 10:00:00");
		
		String resultJson = HttpClientUtil.doGet("http://132.147.0.7/csp/lis3/WedoApp.LISService.cls",params);
		
		List<String> fileList = new ArrayList<>();
		
		Result result = Analysis_Xml.getBasicDataIdList(resultJson);
		if(result.isSuccess()){
			List<Integer> reportIds =(List<Integer>) result.getData();
			if(CollectionUtils.isNotEmpty(reportIds)){
				for (Integer reportId : reportIds) {
					params = new HashMap<>();
					params.put("soap_method", "GetReport");
					params.put("reportId", reportId+"");
					try {
						
						String reportJson = HttpClientUtil.doGet("http://132.147.0.7/csp/lis3/WedoApp.LISService.cls",params);
						if(StringUtils.isNotEmpty(reportJson)){
							FileUtil.createOrEditFile(reportJson, "D://xml", reportId+".xml");
							//FileReader reader = new FileReader(new File("D://xml/"+reportId+".xml"));
							fileList.add("D://xml/"+reportId+".xml");
						}
					} catch (Exception e) {
						continue;
					}
				}
				
			}
			
			
			if(CollectionUtils.isNotEmpty(fileList)){
				for (String fileName : fileList) {
					FileReader reader = new FileReader(new File(fileName));
					String str = "";
					char[] c = new char[1024];
					int length = 0;
					while((length = reader.read(c))!=-1) {
						str+=new String(c, 0, length);
					}
					
			         Object obj = Analysis_Xml.getCheckReportOrderDetailMsg(str).getData();
			         System.out.println(obj);
					// System.out.println(ReportRoot.getReport().getReportItems());
				}
			}
			//http://132.147.0.7/csp/lis3/WedoApp.LISService.cls?soap_method=GetReport&reportId=5027936
		//	Analysis_Xml.getCheckReportOrderDetailMsg(xmlStr)
		}
		
	
		
		
		return "nihao";
	}
	
	@ResponseBody
	@RequestMapping("/parseReport")
	public String parseReport() throws IOException, ParseException{
		File file = new File("D://xml");
		if(file.exists()){
			File[] fileList= file.listFiles();
			HospitalVisitExaminationReportsInfo hospitalVisitExaminationReportsInfo = new HospitalVisitExaminationReportsInfo();
			List<HospitalVisitExaminationReportsRecord> hospitalVisitExaminationReportsRecordList= Lists.newArrayList();
			for (File file2 : fileList) {
				if(file2.isFile()){
					FileReader reader = new FileReader(file2);
					String str = "";
					char[] c = new char[1024];
					int length = 0;
					while((length = reader.read(c))!=-1) {
						str+=new String(c, 0, length);
					}
					
					//ReportRoot [code=1, msg=成功, 
					//report=Report 
					//[name=刘福安,
					//orderDept=心脏中心二病区, testSN=109, gender=男,
					//bedNo=+42床, barcode=0151062830, age=66岁, 
					//chargeType=医疗保险, specimen=全血, mrn=D4207, 
					//orderDoctor=杜大勇, diagnosis=冠状动脉粥样硬化性心脏病, 
					//testsOrdered=血液分析仪血细胞分析,C反应蛋白（进口试剂快速法）, 
					//dtOrder=2017-11-27 10:54, dtSample=2017-11-28 07:07:54,
					//dtAccept=2017-11-28 09:10, dtValid=2017-11-28 09:36:12,
					//techAccept=王建伟, techTest=王建伟, techValid=顾李霖, 
					//reportItems=
					//[ReportItem [name=C反应蛋白, result=<0.020, refRange=<0.8, flag=null, unit=mg/dl]]]]
					
					ReportRoot reportRoot=(ReportRoot) Analysis_Xml.getCheckReportOrderDetailMsg(str).getData();
					HospitalVisitExaminationReportsRecord hospitalVisitExaminationReportsRecord = new HospitalVisitExaminationReportsRecord();
					if(reportRoot!=null){
						Report report = reportRoot.getReport();
						hospitalVisitExaminationReportsRecord.setTitle(report.getTestsOrdered()==null?"":report.getTestsOrdered());
						hospitalVisitExaminationReportsRecord.setPatientName(report.getName()==null?"":report.getName());
						hospitalVisitExaminationReportsRecord.setAgeName(report.getAge()==null?"":report.getAge());
						hospitalVisitExaminationReportsRecord.setDeptCategoryName(report.getOrderDept()==null?"":report.getOrderDept());
						hospitalVisitExaminationReportsRecord.setSpecimenCode(report.getBarcode()==null?"":report.getBarcode());
						hospitalVisitExaminationReportsRecord.setSexName(report.getGender()==null?"":report.getGender());
						hospitalVisitExaminationReportsRecord.setBedName(report.getBedNo()==null?"":report.getBedNo());
						hospitalVisitExaminationReportsRecord.setBarCode(report.getBarcode()==null?"":report.getBarcode());
						hospitalVisitExaminationReportsRecord.setCostName(report.getChargeType()==null?"":report.getChargeType());
						hospitalVisitExaminationReportsRecord.setSpecimenTypeName(report.getSpecimen()==null?"":report.getSpecimen());
						hospitalVisitExaminationReportsRecord.setMrId(report.getMrn()==null?"":report.getMrn());
						hospitalVisitExaminationReportsRecord.setSubmittingPhysicianName(report.getOrderDoctor()==null?"":report.getOrderDoctor());
						hospitalVisitExaminationReportsRecord.setClinicalDiagnosisName(report.getDiagnosis()==null?"":report.getDiagnosis());
						hospitalVisitExaminationReportsRecord.setSamplingDateTime(report.getDtOrder()==null?null:DateUtil.dateParse("yyyy-MM-dd HH:mm",report.getDtOrder()));
						hospitalVisitExaminationReportsRecord.setInspectDateTime(report.getDtSample()==null?null:DateUtil.dateParse("yyyy-MM-dd HH:mm:ss",report.getDtSample()));
						hospitalVisitExaminationReportsRecord.setInspectionDoctorName(report.getTechTest()==null?"":report.getTechTest());
						hospitalVisitExaminationReportsRecord.setAcceptanceCheckDateTime(report.getDtAccept()==null?null:DateUtil.dateParse("yyyy-MM-dd HH:mm",report.getDtAccept()));
						hospitalVisitExaminationReportsRecord.setReportDateTime(report.getDtValid()==null?null:DateUtil.dateParse("yyyy-MM-dd HH:mm:ss",report.getDtValid()));
						hospitalVisitExaminationReportsRecord.setAuditorDoctorName(report.getTechValid()==null?"":report.getTechValid());
						if(report!=null){
							List<ReportItem> reportItems = report.getReportItems();
							List<HospitalVisitExaminationReportsItem> hospitalVisitExaminationReportsItemList = Lists.newArrayList();
							HospitalVisitExaminationReportsItem hospitalVisitExaminationReportsItem=null;
							if(CollectionUtils.isNotEmpty(reportItems)){
								for (ReportItem reportItem : reportItems) {
									hospitalVisitExaminationReportsItem = new HospitalVisitExaminationReportsItem();
									hospitalVisitExaminationReportsItem.setProjectName(reportItem.getName()==null?"":reportItem.getName());
									hospitalVisitExaminationReportsItem.setExaminationResult(reportItem.getResult()==null?"":reportItem.getResult());
									hospitalVisitExaminationReportsItem.setExaminationResultMark(reportItem.getFlag()==null?"":reportItem.getFlag());
									hospitalVisitExaminationReportsItem.setExaminationUnit(reportItem.getUnit()==null?"":reportItem.getUnit());
									hospitalVisitExaminationReportsItem.setReferenceValues(reportItem.getRefRange()==null?"":reportItem.getRefRange());
									hospitalVisitExaminationReportsItemList.add(hospitalVisitExaminationReportsItem);
									
								}
							}
							
							hospitalVisitExaminationReportsRecord.setExaminationReportsItems(hospitalVisitExaminationReportsItemList);
						}
						hospitalVisitExaminationReportsRecordList.add(hospitalVisitExaminationReportsRecord);
					}
					
					hospitalVisitExaminationReportsInfo.setExaminationReportsRecords(hospitalVisitExaminationReportsRecordList);
				}
			}
		}
		
		return "";
	}
	
	
	@ResponseBody
	@RequestMapping("/nurseReport")
	public String nursrRecord(){
		
		return "success";
	}

	
}
